import * as vscode from "vscode";
export function handle_for_select(textEditor: vscode.TextEditor, edit: vscode.TextEditorEdit) {
    const position = textEditor.selection.active;
    const [line, col] = [position.line, position.character];
    const positionLinetext = textEditor.document.lineAt(line); // 当行文本

    // 重新选择selection
    const select_range = (start: number, end: number) => {
        let start_postion = new vscode.Position(line, start);
        let end_position = new vscode.Position(line, end + 1);
        textEditor.selection = new vscode.Selection(start_postion, end_position);
    }
    for (let iter_col of [col, Math.max(0, col - 1)]) {
        let [is_ok, [start, end]] = get_range(positionLinetext.text,
            iter_col)
        if (is_ok) {
            select_range(start, end);
            break;
        }
    }


}
export async function handle_select_and_open_in_file(textEditor: vscode.TextEditor, edit: vscode.TextEditorEdit) {
    let position = textEditor.selection.active;
    let [line, col] = [position.line, position.character];
    const positionLinetext = textEditor.document.lineAt(line); // 当行文本
    let select_range: [number, number] | null = null;
    let selection = textEditor.selection;
    let selections = textEditor.selections;
    // textEditor.vi
    let line_text = positionLinetext.text;
    if(selection.start.character != selection.end.character) {
        select_range = [selection.start.character, selection.end.character];
        let selected_text = line_text.slice(select_range[0], select_range[1]);
        await vscode.commands.executeCommand("workbench.action.quickOpen", selected_text)
    } else {
        for (let walk_col of [col, Math.max(0, col - 1)]) {
            let [is_ok, current_range] = get_range(positionLinetext.text, walk_col);
            if (is_ok) {
                select_range = [current_range[0], current_range[1]];
                break;
            }
        }
        if (!select_range) {
            vscode.window.showErrorMessage(`cannot get select in line [${positionLinetext.text}]`)
            return;
        }
        let selected_text = line_text.slice(select_range[0], select_range[1] + 1);
        await vscode.commands.executeCommand("workbench.action.quickOpen", selected_text)
    }
    
    
    // let selected_text = line_text.slice(select_range[0], select_range[1] + 1);
    // await vscode.commands.executeCommand("workbench.action.quickOpen", selected_text)
}


export async function handle_select_and_open_in_dir(textEditor: vscode.TextEditor, edit: vscode.TextEditorEdit) {
    // 打开文件加
    let position = textEditor.selection.active;
    let [line, col] = [position.line, position.character];
    const positionLinetext = textEditor.document.lineAt(line); // 当行文本
    let select_range: [number, number] | null = null;
    for (let walk_col of [col, Math.max(0, col - 1)]) {
        let [is_ok, current_range] = get_range(positionLinetext.text, walk_col);
        if (is_ok) {
            select_range = [current_range[0], current_range[1]];
            break;
        }
    }
    if (!select_range) {
        vscode.window.showErrorMessage(`cannot get select in line [${positionLinetext.text}]`)
        return;
    }
    // 暂时只处理linux的/ 不处理windows的\\

    let line_text = positionLinetext.text;
    let selected_text = line_text.slice(select_range[0], select_range[1] + 1);
    if (selected_text.indexOf("/") == -1) {
        vscode.window.showErrorMessage(`路劲没有文件夹 [${selected_text}]`)
        return
    }
    let slice: Array<string> = selected_text.split("/")
    if (slice.length == 2) {
        await vscode.commands.executeCommand("workbench.action.quickOpen", slice[0] + "/")
        return;
    }


    let stringprefix = (value: string, count: number): string => {
        let prefix = "0".repeat(count);
        let tmp = prefix + value;
        return tmp.slice(tmp.length - count);
    }



    let quickItemList: vscode.QuickPickItem[] = [];
    for (let i = 0; i < slice.length - 1; i++) {
        let tag = slice[i];
        let prefix = stringprefix('' + i, 2);
        quickItemList.push({
            "label": `${prefix}.${tag}`,
            "description": tag

        })

    }


    let itemList = await vscode.window.showQuickPick(quickItemList, { canPickMany: true })

    if (!itemList) {
        return;
    }
    let startItem: vscode.QuickPickItem, endItem: vscode.QuickPickItem
    if (itemList.length == 1) {
        startItem = itemList[0]
        endItem = itemList[0]
    } else {
        startItem = itemList[0]
        endItem = itemList[itemList.length - 1]
    }
    // let { label, description } = item;
    let startIndex: number = -1, endIndex: number = -1;

    for (let i = 0; i < slice.length; i++) {
        let tag = slice[i];

        if (tag == startItem.description) {
            startIndex = i;
            // addTag(tag);
            // await vscode.commands.executeCommand("workbench.action.quickOpen", tag);
        }// if(title==description)
        if (tag == endItem.description) {
            endIndex = i;
        }
    }

    let desc = slice.slice(startIndex, endIndex + 1).join("/") + "/";

    let activeEditor = vscode.window.activeTextEditor!;
    // edit.insert(position, desc)
    activeEditor.insertSnippet(new vscode.SnippetString(desc), textEditor.selection.active)


}

function get_or_undefined_char_at_position(line: string, col: number) {
    if (line.length <= col) {
        return undefined;
    }
    return line.charAt(col);
}
/**
 * 
 * @param line 当前行的内容
 * @param findeIndex 找到单引号或者双引号的位置
 * @param currentCol 当前鼠标的位置
 * @param expected 单引号或者双引号
 */
function handle_for_quote(line: string, findeIndex: number, currentCol: number, expected: string = '"'): [boolean, [number, number]] {
    const _get_or_undefine_char_at_position = (col: number) => {
        if (line.length <= col) {
            return undefined;
        }
        return line.charAt(col);
    }

    if (_get_or_undefine_char_at_position(findeIndex + 1) == expected && _get_or_undefine_char_at_position(findeIndex + 2) == expected) {
        // 不处理多行字符串
        return [false, [0, 0]];
    }
    // if(_get_or_undefine_char_at_position(currentCol) === undefined || _get_or_undefine_char_at_position(currentCol) === " ") {
    //     return [false, [0, 0]];
    // }
    if (findeIndex >= currentCol) {
        //当前位置不再字符串里面, 获取变量的范围
        // 1. 获取start
        let start = currentCol - 1;
        for (; start >= 0; start--) {
            let ch = _get_or_undefine_char_at_position(start);
            if (ch === undefined || !/[_a-zA-Z]/.test(ch)) {
                break
            }
        }
        // 2. 获取end
        let end = currentCol
        for (; end < line.length - 1; end++) {
            let ch = _get_or_undefine_char_at_position(start);
            if (ch === undefined || !/[_a-zA-Z]/.test(ch)) {
                break
            }
        }
        return [true, [start + 1, end - 1]];
        // select_range(start + 1, end - 1);
    } else {
        // 获取字符串的范围
        let start = currentCol - 1
        for (; start >= findeIndex; start--) {
            let ch = _get_or_undefine_char_at_position(start);
            if (ch === expected) {
                if (_get_or_undefine_char_at_position(start - 1) !== '\\') {
                    break;
                }
            }

        }
        // 2. 获取end
        let end = currentCol
        for (; end < line.length; end++) {
            let ch = _get_or_undefine_char_at_position(end);
            if (ch === undefined) {
                throw Error("cannot find end char");
            }
            if (ch === expected) {
                if (_get_or_undefine_char_at_position(start - 1) !== '\\') {
                    break;
                }
            }
        }
        return [true, [start + 1, end - 1]];
        // select_range(start + 1, end - 1);
    }
}

export function get_range(line: string, currentCol: number): [boolean, Array<number>] {
    let col = currentCol;
    const indexOfFirstdoubleQuote = line.indexOf('"');
    const indexOfFirstSingleQuote = line.indexOf("'");
    // let match_result;
    if (indexOfFirstdoubleQuote <= col && (Math.abs(col - indexOfFirstdoubleQuote) < Math.abs(col - indexOfFirstSingleQuote)) && indexOfFirstdoubleQuote > -1) {
        let match_result = handle_for_quote(line, indexOfFirstdoubleQuote, col, '"');
        return match_result

    }


    if (indexOfFirstSingleQuote <= col && indexOfFirstSingleQuote > -1) {
        let match_result = handle_for_quote(line, indexOfFirstSingleQuote, col, "'");
        return match_result;
    }
    // 处理变量
    let [start, end] = [col, col];
    let current_ch = get_or_undefined_char_at_position(line, col);
    if (current_ch === undefined || current_ch === " ") {
        return [false, [0, 0]];
    }
    let ch, prev_ch
    while (1) {
        ch = get_or_undefined_char_at_position(line, start);
        if (ch === undefined || !/[_a-zA-Z0-9.]/.test(ch)) {
            break;
        }
        prev_ch = ch
        start--;
    }
    [ch, prev_ch] = '', ''
    while (1) {
        ch = get_or_undefined_char_at_position(line, end);
        if (ch === undefined || !/[_a-zA-Z0-9.]/.test(ch)) {
            break;
        }
        prev_ch = ch;
        end++;
    }
    return [true, [start + 1, end - 1]]
}